package com.gym.core.date;

import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * 2015-1-5 下午5:26:59
 */
public abstract class DateContants {
	public static final long ONE_DAY = 24 * 60 * 60 * 1000L;
    public static final long ONE_HOUR = 60 * 60 * 1000L;
    public static final long ONE_MINUTE = 60 * 1000L;
    public static final long ONE_SECOND = 1000L;
    
    
	public static final SimpleDateFormat[] FORMAT_YYYY_MM_DD = createDateFormat("yyyy-MM-dd");
	public static final SimpleDateFormat[] FORMAT_YYYY_MM_DD_HH_MM_SS = createDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final SimpleDateFormat[] FORMAT_YYYYMMDD = createDateFormat("yyyyMMdd");
	public static final SimpleDateFormat[] FORMAT_YYYYMMDDHHMMSS = createDateFormat("yyyyMMddHHmmss");
	
	private static final int INSTANCE_COUNT = 20;
	private static AtomicInteger currentIndex = new AtomicInteger(0); // 不需要考虑多线程问题，节省性能开销。
	
	private static SimpleDateFormat[] createDateFormat(String fmt) {
    	SimpleDateFormat[] ret = new SimpleDateFormat[INSTANCE_COUNT];
    	for (int i = 0; i < ret.length; i++) {
    		ret[i] = new SimpleDateFormat(fmt);
    		ret[i].setLenient(false);
    	}
		return ret;
	}
	
	
	private final  static int getIndex() {
    	int n = currentIndex.getAndIncrement();
    	if (n < 0) { // 处理溢出
    		currentIndex = new AtomicInteger(0);
    		n = 0;
    	}
    	return n % INSTANCE_COUNT;
    }
	
	
	public static SimpleDateFormat getDateFormat(DateFormatType formatType){
		if(DateFormatType.YYYY_MM_DD.equals(formatType)){
			return FORMAT_YYYY_MM_DD[DateContants.getIndex()]; 
		} else if(DateFormatType.YYYY_MM_DD_HH_MM_SS.equals(formatType)){
			return FORMAT_YYYY_MM_DD_HH_MM_SS[DateContants.getIndex()]; 
		}else if(DateFormatType.YYYYMMDD.equals(formatType)){
			return FORMAT_YYYYMMDD[DateContants.getIndex()]; 
		}else if(DateFormatType.YYYYMMDDHHMMSS.equals(formatType)){
			return FORMAT_YYYYMMDDHHMMSS[DateContants.getIndex()]; 
		}
		return null;
	}
	
	public static enum DateFormatType {
		YYYY_MM_DD("yyyy-MM-dd"),
		YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd HH:mm:ss"),
		YYYYMMDD("yyyyMMdd"),
		YYYYMMDDHHMMSS("yyyyMMddHHmmss");
		private String formate;
		private DateFormatType(String format){
			this.formate = format;
		}
		public String getFormate() {
			return formate;
		}
		
	}
}
